<?php

namespace app\admin\controller;

use app\admin\model\{UploadFile,Setting as SettingModel, UploadGroup};
/**
 * 文件库管理
 * Class Upload
 * @package app\store\controller
 */
class Upload extends Controller
{
    private $config;

    /**
     * 构造方法
     * @throws \app\common\exception\BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function initialize()
    {
        parent::initialize();
        // 存储配置信息
        $this->config = SettingModel::getItem('storage');
    }

    /**
     * 图片上传接口
     * @param int $group_id
     * @return array
     * @throws \think\Exception
     */
    public function image()
    {
        $files = request()->file('file');
        $fileName = $files->hashName();
        $group_id = $this->request->param('group_id');
        if (!$file = \think\facade\Filesystem::disk('public')->putFileAs('',$files,$fileName)) {
            return $this->renderError('上传图片失败');
        }
        $uploadFile = $this->addUploadFile($group_id,$fileName,$files,'image');
        $uploadFile['file_id'] = $uploadFile['id'];
        return $this->renderSuccess($uploadFile);
    }

    /**
     * 添加文件库上传记录
     * @param $group_id
     * @param $fileName
     * @param $fileInfo
     * @param $fileType
     * @return UploadFile
     */
    private function addUploadFile($group_id, $fileName, $fileInfo, $fileType)
    {
        // 存储引擎
        $storage = $this->config['default'];
        // 存储域名
        $fileUrl = isset($this->config['engine'][$storage]['domain'])
            ? $this->config['engine'][$storage]['domain'] : '';
        // 添加文件库记录
        $model = new UploadFile;
        $model->add([
            'group_id' => $group_id > 0 ? (int)$group_id : 0,
            'storage' => $storage,
            'file_url' => $fileUrl,
            'file_name' => $fileName,
            'file_size' => $fileInfo->getSize(),
            'file_type' => $fileType,
            'extension' => pathinfo($fileInfo->getFileInfo(), PATHINFO_EXTENSION),
        ]);
        return $model;
    }

}
